package org.sky.util;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author weifx
 * @Title: BeanUtils
 * @ProjectName springboot-platform
 * @Description: TODO{Bean反射工具类}
 * @date 2019/2/26 16:31
 * @Version 1.0
 */
public class BeanUtils {
    public static final char UNDERLINE = '_';

    /**
     * 驼峰值转下划线
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if(StringUtils.isBlank(param)){
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线转驼峰值
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if(StringUtils.isBlank(param)) {
            return "";
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            // String.valueOf(Character.toUpperCase(sb.charAt(position)));
            sb.replace(position - 1, position + 1,
                    sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 下划线Key值转实体Bean
     * @param underlineColumn
     * @param clazz
     * @return
     */
    public static <T> T invokeBean(Map<String,Object> underlineColumn, Class<T> clazz){
        Map tempField = new HashMap();
        for(Map.Entry<String,Object> entry:underlineColumn.entrySet()){
            String ColumnName = (String)entry.getKey();
            tempField.put(underlineToCamel(ColumnName.toLowerCase()),entry.getValue());
        }
        return JsonUtils.map2pojo(tempField,clazz);
    }
    /**
     * 获取类的所有属性
     * @param list
     * @param clazz
     * @return
     */
    public static List<Field> getAllField(List<Field> list, Class clazz){
        if(!clazz.equals(Object.class)){
            Field[] f=clazz.getDeclaredFields();
            for(int i=0;i<f.length;i++){
                list.add(f[i]);
            }
            getAllField(list,clazz.getSuperclass());
        }
        return list;
    }
}
